package com.qf.controller;

import com.qf.service.UserService;
import com.qf.service.UserServiceImpl;
import com.qf.utils.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Hou
 * @version V1.0
 * @Project
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 */
@WebServlet(name = "UserController",urlPatterns = "/login")
public class UserController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取前端传入的参数。
        String username = request.getParameter("username");
        String password = request.getParameter("password");

//

        //判断用户名密码是否为空
        if(MyUtil.isEmpty(username) || MyUtil.isEmpty(password)){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }

        //走登录的逻辑 调用业务层的内容
        UserService service = new UserServiceImpl();
        boolean result = service.login(username,password);
        HttpSession session = request.getSession();
        if(result){
            session.setAttribute("username", username);
            //登录成功
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }else{
            //登录失败，重新登录
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
